#!/bin/sh
#package:odpkg
#desc:Update package list
#type:multiple

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later

#Sysrep is not stored in the configuration. It's only in the initrd
CONFIGFILE='/etc/opendomo/repositories.cfg'
mkdir -p /var/pkg/installed/
touch $CONFIGFILE

SPATH="`cat $CONFIGFILE`"
PKGLIST="/tmp/allavailable.txt"
URLLIST="/tmp/urlavailable.txt"
PLATFORMLIST="/tmp/platformavailable.txt"
TMPLIST="/tmp/tmppkglist"

echo > $PKGLIST
echo > $URLLIST
echo > $TMPLIST
chown admin:admin $PKGLIST $URLLIST $TMPLIST 2>/dev/null

uid=`cat /etc/opendomo/uid` 2>/dev/null
ver=`cat /etc/VERSION` 2>/dev/null

tmpf="/tmp/tmpfile.tmp"
echo "#LOADING Downloading package information"
echo
for w in $SPATH
do
	touch $tmpf
	if wget -q -O $tmpf "$w?UID=$uid&VER=$ver" 2>/dev/null
	then
		echo "# downloading from [$w] "
		desc=`grep '#desc' $tmpf | cut -f2- -d' '`
		if test -z "$desc"; then
			echo "#WARN Invalid repository [$w]"
			sleep 2
		fi
		k=`echo $w | cut -f2 -d: | sed 's/[^a-z]//g'`
		cat $tmpf | grep -v "#" > $TMPLIST  
		for f in `cat $TMPLIST | cut -f1 -d';'`; do
			CODE=`echo $f | cut -f1 -d'.'`
			SHA1=`grep $f $TMPLIST | cut -f3 -d';'`
			echo "$CODE;${w}/${f};$SHA1" >> $URLLIST
		done
		PF=`grep - $URLLIST | wc -l`
		echo "# Found [$PF] packages"
		cat $TMPLIST >> $PKGLIST
	else
		echo "#WARN Invalid repository [$w]"
		sleep 2
	fi 
done
echo
	
# In this point, we must have 2 text plain file with the following structure:
# $URLLIST
# http://es.opendomo.org/files/pkg/pkgname-20120509.x86.tar.gz	

# $PKGLIST
# pkgname;sha1;dep1,dep2
	
# Solamente se muestran los paquetes disponibles para la plataforma actual
if test -f /etc/archs; then
	ARCH="-e .noarch.t -e `cat /etc/archs | sed 's/|/.t -e ./g'`.t "
else
	ARCH='-e .noarch.t -e 86.t'
fi
#grep -e "\(noarch\|$ARCH\).tar" $PKGLIST.txt | sort | uniq > "$PLATFORMLIST"

#echo "#ERR: grep $ARCH $PKGLIST"
grep $ARCH  $PKGLIST | sort | uniq > "$PLATFORMLIST"

for i in `grep -v "^_" $PLATFORMLIST | cut -f 1 -d'-' |  uniq | sort`; do
	URL=`grep "/$i-" $URLLIST | cut -f2 -d';'|  head -n 1 | cut -f 1 -d'-'`
	wget -q $URL.desc -O - > /tmp/$i.info 2>/dev/null 
done

rm -f $TMPLIST

